package Backtracking;

import java.util.ArrayList;
import java.util.List;

/*
* Offer34.目标和
*
*   根节点到叶子结点等于给定的目标和
 *
* */
 class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Offer34pathSum {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> list=new ArrayList<>();
    int sum=0;
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        if(root==null){
            return res;
        }
        backtrack(root,target);
        return res;
    }
    private void backtrack(TreeNode root, int target) {
        if(root==null){
            return;
        }
        sum+=root.val;
        list.add(root.val);
        if(root.left==null && root.right==null && sum==target){
            res.add(new ArrayList<>(list));
            return;
        }
        backtrack(root.left, target);
        backtrack(root.right, target);
        sum-=root.val;
        list.remove(list.size()-1);
    }
}
